﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Diagnostics;

namespace CountdownCalendar.Converters
{
    public class TimeLeftConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            DateTime date;
            ObjectDataProvider odp = parameter as ObjectDataProvider;
            Settings settings = odp.ObjectInstance as Settings;
            if (value != null)
            {
                bool isValid = StringToDateTime.GetDateTime(value.ToString(), out date);
                if (isValid)
                {
                    TimeSpan span = date - DateTime.Now;
                    if (settings.WeekDaysOnly)
                    {
                        int daysLeft = span.Days + 1;
                        DateTime day = DateTime.Now;
                        int i=0;
                        while (day.Day != date.Day || day.Month != date.Month || day.Year != date.Year)
                        {
                            i++;
                            day = DateTime.Now.AddDays(i);
                            if (day.DayOfWeek == DayOfWeek.Saturday || day.DayOfWeek == DayOfWeek.Sunday)
                                daysLeft--;
                        }
                        return daysLeft;
                    }

                    return span.Days + 1;                   
                    
                }
                else
                {
                    return "?";
                }
            }
            else
                return "?";
        }


        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
